package com.silence.reflection;

import java.io.FileOutputStream;
import java.io.PrintStream;
import java.lang.reflect.Field;

public class ObjectSaveReflection {
    // 接收任意对象，将对象和每个字段的值都保存到文件中去
    public static void saveObject(Object obj) throws Exception {
        PrintStream ps = new PrintStream(new FileOutputStream("helloworld-app\\src\\com\\silence\\reflection\\saveObject\\data.txt", true));
        // 对象
        Class c = obj.getClass();
        String simpleClassName = c.getSimpleName();
        ps.println("--------------------" + simpleClassName + "--------------------");
        // 拿变量
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            String name = field.getName();
            field.setAccessible(true);
            String value =  field.get(obj)+" ";
            ps.println(name + " = " + value);
        }
        ps.println("----------------------------------------");
        ps.close();
        System.out.println("save finish");
    }
}
